#!/bin/bash

#================================================================================
# frps & frpc 一键安装与管理脚本 (二合一) - 修复版
#
# Author: 错弦序
# 修复: 下载失败问题
#
# 功能:
#   - 启动时自动检测 frps/frpc 服务状态
#   - 自由选择安装服务端(frps)或客户端(frpc)
#   - [服务端] 自动配置、生成随机Token、管理服务
#   - [客户端] 交互式配置、引导式添加代理、管理服务
#   - 一键更新版本 (保留配置)
#   - 显示连接信息 & 保存到日志
#   - 一键安全卸载
#   - 新增: 手动指定版本号安装
#   - 新增: journalctl日志查看功能
#   - 新增: login_fail_exit配置选项
#   - 新增: 菜单中显示服务状态
#   - 新增: 配置编辑功能
#   - 新增: Alpine Linux和Arch Linux支持
#
#================================================================================

# --- 全局变量 ---
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 文件路径
FRP_BASE_PATH="/usr/local/frp"
ETC_FRP_PATH="/etc/frp"
FRPS_CONFIG_FILE="${ETC_FRP_PATH}/frps.toml"
FRPC_CONFIG_FILE="${ETC_FRP_PATH}/frpc.toml"
FRPS_INFO_LOG="${ETC_FRP_PATH}/frps_installed_info.log"
SYSTEMD_PATH="/etc/systemd/system"
GITHUB_API_URL="https://api.github.com/repos/fatedier/frp/releases/latest"

# 按任意键继续函数
press_any_key() {
    echo ""
    read -n 1 -s -r -p "按任意键返回菜单..."
}

# --- 通用辅助函数 ---

check_root() {
    if [ "$(id -u)" -ne 0 ]; then
        echo -e "${RED}错误：此脚本必须以 root 用户权限运行。${NC}"
        echo -e "请尝试使用 'sudo ./frp_manager.sh' 命令运行。"
        exit 1
    fi
}

check_dependencies() {
    echo -e "${BLUE}正在检查系统依赖...${NC}"
    local dependencies=("curl" "wget" "tar")
    local pkg_manager=""
    if command -v apt-get &>/dev/null; then 
        pkg_manager="apt-get"
    elif command -v yum &>/dev/null; then 
        pkg_manager="yum"
    elif command -v apk &>/dev/null; then 
        pkg_manager="apk"
    elif command -v pacman &>/dev/null; then 
        pkg_manager="pacman"
    else
        echo -e "${RED}错误：不支持的包管理器。请手动安装 curl, wget, tar。${NC}"
        exit 1
    fi
    local missing_deps=()
    for dep in "${dependencies[@]}"; do
        if ! command -v "$dep" &>/dev/null; then missing_deps+=("$dep"); fi
    done
    if [ ${#missing_deps[@]} -gt 0 ]; then
        echo -e "${YELLOW}检测到缺失的依赖：${missing_deps[*]}，正在尝试自动安装...${NC}"
        if [ "$pkg_manager" == "apk" ]; then
            sudo $pkg_manager update &>/dev/null
            sudo $pkg_manager add "${missing_deps[@]}"
        elif [ "$pkg_manager" == "pacman" ]; then
            sudo $pkg_manager -Sy --noconfirm "${missing_deps[@]}"
        else
            sudo $pkg_manager update &>/dev/null
            sudo $pkg_manager install -y "${missing_deps[@]}"
        fi
        if [ $? -ne 0 ]; then echo -e "${RED}依赖安装失败，请手动安装后重试。${NC}"; exit 1; fi
    fi
}

get_arch() {
    case "$(uname -m)" in
        x86_64 | amd64) echo "amd64" ;;
        aarch64 | arm64) echo "arm64" ;;
        armv7l) echo "arm" ;;
        *) echo "amd64" ;;
    esac
}

get_latest_version() {
    local latest_version=$(curl -sSL "$GITHUB_API_URL" | grep '"tag_name":' | sed -E 's/.*"v([^"]+)".*/\1/')
    if [ -z "$latest_version" ]; then
        echo -e "${RED}获取最新版本号失败，请检查网络或稍后再试。${NC}"; return 1; fi
    echo "v$latest_version"
}

download_and_extract() {
    local version_opt="$1"
    local download_url
    local version
    local arch=$(get_arch)

    if [ "$arch" == "unsupported" ]; then
        echo -e "${RED}错误：不支持的系统架构: $(uname -m)${NC}"; return 1;
    fi

    # 处理手动指定版本
    if [[ "$version_opt" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        version="$version_opt"
    elif [ "$version_opt" == "latest" ]; then
        version=$(get_latest_version)
        if [[ $? -ne 0 ]]; then
            # 如果获取最新版失败，使用稳定的v0.61.0版本
            echo -e "${YELLOW}无法获取最新版本，将使用稳定的 v0.61.0 版本${NC}"
            version="v0.61.0"
        fi
    else
        # 指定版本
        version="v0.61.0"
    fi

    # 修复下载链接构造
    local version_num=${version#v}  # 移除开头的v
    download_url="https://github.com/fatedier/frp/releases/download/${version}/frp_${version_num}_linux_${arch}.tar.gz"

    echo -e "${GREEN}将安装版本: ${version}, 架构: ${arch}${NC}"
    echo -e "${BLUE}下载地址: ${download_url}${NC}"

    # 增加重试机制
    local max_retries=3
    local retry=0
    while [ $retry -lt $max_retries ]; do
        echo -e "${BLUE}正在下载 frp 安装包... (尝试 $((retry+1))/${max_retries})${NC}"
        wget -qO "/tmp/frp.tar.gz" "$download_url"
        if [ $? -eq 0 ]; then
            break
        fi
        echo -e "${YELLOW}下载失败，正在重试...${NC}"
        sleep 2
        retry=$((retry+1))
    done

    if [ $retry -eq $max_retries ]; then
        echo -e "${RED}下载失败，请检查网络连接或手动下载。${NC}"
        return 1
    fi

    echo -e "${BLUE}正在解压安装包...${NC}"
    local extracted_dir_name=$(tar -tf /tmp/frp.tar.gz | head -1 | cut -f1 -d"/")
    tar -zxf "/tmp/frp.tar.gz" -C "/tmp"
    FRP_TMP_PATH="/tmp/${extracted_dir_name}"
    return 0
}

stop_and_disable_service() {
    local service_name="$1"
    if systemctl is-active --quiet "$service_name"; then
        echo -e "${BLUE}正在停止 ${service_name} 服务...${NC}"
        sudo systemctl stop "$service_name"
    fi
    if systemctl is-enabled --quiet "$service_name"; then
        echo -e "${BLUE}正在禁用 ${service_name} 服务...${NC}"
        sudo systemctl disable "$service_name"
    fi
}

# --- FRPS 服务端函数 ---

configure_frps() {
    local version="$1"
    if [ -f "$FRPS_CONFIG_FILE" ]; then echo -e "${YELLOW}检测到现有服务端配置文件，将保留原有设置。${NC}"; return; fi

    echo -e "${BLUE}--- 开始配置 frps (服务端) ---${NC}"
    sudo mkdir -p "$ETC_FRP_PATH"
    read -rp "请输入 frps 的绑定端口 (bindPort) [默认为 7000]: " bind_port; bind_port=${bind_port:-7000}
    read -rp "是否需要自动生成一个随机认证令牌 (token)？(y/n) [默认为 y]: " gen_token; gen_token=${gen_token:-y}
    local token
    if [[ "$gen_token" == "y" || "$gen_token" == "Y" ]]; then
        token=$(head /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 16)
        echo -e "${GREEN}已生成随机 token: ${token}${NC}"
    else read -rp "请输入您的自定义 token: " token; fi

    read -rp "是否需要启用仪表盘 (Dashboard)？(y/n) [默认为 y]: " enable_dashboard; enable_dashboard=${enable_dashboard:-y}
    local dashboard_port user pwd
    if [[ "$enable_dashboard" == "y" || "$enable_dashboard" == "Y" ]]; then
        read -rp "请输入仪表盘端口 (dashboardPort) [默认为 7500]: " dashboard_port; dashboard_port=${dashboard_port:-7500}
        user="admin"; pwd=$(head /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 12)
        echo -e "${GREEN}仪表盘用户名固定为: ${user}，已生成随机密码: ${pwd}${NC}"
    fi

    echo -e "${BLUE}正在生成服务端配置文件: ${FRPS_CONFIG_FILE}${NC}"
    sudo tee "$FRPS_CONFIG_FILE" > /dev/null <<EOF
bindPort = $bind_port
auth.token = "$token"
EOF
    if [[ "$enable_dashboard" == "y" || "$enable_dashboard" == "Y" ]]; then
        sudo tee -a "$FRPS_CONFIG_FILE" > /dev/null <<EOF
webServer.addr = "0.0.0.0"
webServer.port = $dashboard_port
webServer.user = "$user"
webServer.password = "$pwd"
EOF
    fi
    local public_ip=$(curl -s ip.sb) || public_ip="<无法获取>"
    sudo tee "$FRPS_INFO_LOG" > /dev/null <<EOF
FRP_VERSION="$version"
SERVER_PUBLIC_IP="$public_ip"
BIND_PORT="$bind_port"
AUTH_TOKEN="$token"
DASHBOARD_ENABLED="${enable_dashboard}"
DASHBOARD_PORT="$dashboard_port"
DASHBOARD_USER="$user"
DASHBOARD_PWD="$pwd"
EOF
}

setup_systemd_frps() {
    echo -e "${BLUE}正在为 frps 创建 systemd 服务...${NC}"
    sudo tee "${SYSTEMD_PATH}/frps.service" > /dev/null <<EOF
[Unit]
Description=Frp Server Service
After=network.target
[Service]
Type=simple
User=root
Restart=on-failure
RestartSec=5s
ExecStart=/usr/bin/frps -c ${FRPS_CONFIG_FILE}
[Install]
WantedBy=multi-user.target
EOF
    sudo systemctl daemon-reload; sudo systemctl enable frps; sudo systemctl start frps
    sleep 2
    if systemctl is-active --quiet frps; then echo -e "${GREEN}frps 服务已成功启动！${NC}"; else
        echo -e "${RED}错误：frps 服务启动失败，请检查日志。${NC}"; fi
}

install_frps() {
    local version_opt="$1"
    echo -e "${BLUE}--> 开始安装 frps (服务端)...${NC}"
    if ! download_and_extract "$version_opt"; then return; fi
    sudo mkdir -p "$FRP_BASE_PATH"
    sudo cp "${FRP_TMP_PATH}/frps" "${FRP_BASE_PATH}/frps"
    sudo ln -sfn "${FRP_BASE_PATH}/frps" "/usr/bin/frps"
    sudo chmod +x "/usr/bin/frps"
    configure_frps "$(grep "tag_name" "${FRP_TMP_PATH}/LICENSE" 2>/dev/null | head -n 1 | awk '{print $2}' || echo ${version_opt})"
    setup_systemd_frps
    rm -rf "/tmp/frp.tar.gz" "${FRP_TMP_PATH}"
    show_frps_info
}

show_frps_info() {
    if [ ! -f "$FRPS_INFO_LOG" ]; then echo -e "${RED}错误：未找到服务端连接信息文件。${NC}"; return; fi
    source "$FRPS_INFO_LOG"
    clear
    echo -e "${YELLOW}======================================================${NC}"
    echo -e "${GREEN}          frps (服务端) - 当前连接信息             ${NC}"
    echo -e "${YELLOW}======================================================${NC}"
    echo -e " frp 版本          : ${BLUE}${FRP_VERSION}${NC}"
    echo -e " 服务器公网 IP     : ${BLUE}${SERVER_PUBLIC_IP}${NC}"
    echo -e "\n${YELLOW}--- frpc 客户端配置 ---${NC}"
    echo -e " serverAddr        : ${BLUE}${SERVER_PUBLIC_IP}${NC}"
    echo -e " serverPort        : ${BLUE}${BIND_PORT}${NC}"
    echo -e " token             : ${BLUE}${AUTH_TOKEN}${NC}"
    if [ "$DASHBOARD_ENABLED" == "y" ] || [ "$DASHBOARD_ENABLED" == "Y" ]; then
        echo -e "\n${YELLOW}--- 仪表盘 (Dashboard) 信息 ---${NC}"
        echo -e " 访问地址          : ${BLUE}http://${SERVER_PUBLIC_IP}:${DASHBOARD_PORT}${NC}"
        echo -e " 用户名 (user)     : ${BLUE}${DASHBOARD_USER}${NC}"
        echo -e " 密码 (password)   : ${BLUE}${DASHBOARD_PWD}${NC}"
    fi
    echo -e "\n此信息已保存到: ${GREEN}${FRPS_INFO_LOG}${NC}"
    echo -e "${YELLOW}======================================================${NC}"
}

uninstall_frps() {
    read -rp "$(echo -e ${RED}"警告：此操作将彻底卸载 frps 并删除所有相关文件！确定吗？ (y/n): "${NC})" confirm
    if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then echo -e "${YELLOW}操作已取消。${NC}"; return; fi
    stop_and_disable_service "frps"
    sudo rm -f "/usr/bin/frps" "${FRP_BASE_PATH}/frps" "${SYSTEMD_PATH}/frps.service" "$FRPS_CONFIG_FILE" "$FRPS_INFO_LOG"
    sudo systemctl daemon-reload
    echo -e "${GREEN}frps 已成功卸载。${NC}"
}

# --- FRPC 客户端函数 ---

configure_frpc() {
    if [ -f "$FRPC_CONFIG_FILE" ]; then echo -e "${YELLOW}检测到现有客户端配置文件，将保留原有设置。${NC}"; return; fi

    echo -e "${BLUE}--- 开始配置 frpc (客户端) ---${NC}"
    sudo mkdir -p "$ETC_FRP_PATH"
    read -rp "请输入服务端公网 IP (serverAddr): " server_addr
    read -rp "请输入服务端端口 (serverPort) [默认为 7000]: " server_port; server_port=${server_port:-7000}
    read -rp "请输入服务端的认证令牌 (token): " token
    
    # 新增：login_fail_exit配置
    read -rp "是否设置登陆失败不退出？(y/n) [默认为 y]: " login_fail_exit; login_fail_exit=${login_fail_exit:-y}

    echo -e "${BLUE}正在生成基础配置文件...${NC}"
    sudo tee "$FRPC_CONFIG_FILE" > /dev/null <<EOF
serverAddr = "$server_addr"
serverPort = $server_port
auth.token = "$token"
EOF

    # 添加login_fail_exit配置
    if [[ "$login_fail_exit" == "y" || "$login_fail_exit" == "Y" ]]; then
        sudo tee -a "$FRPC_CONFIG_FILE" > /dev/null <<EOF
login.failExit = false
EOF
    fi

    read -rp "是否现在添加一个代理 (例如，转发SSH)？(y/n) [默认为 y]: " add_proxy; add_proxy=${add_proxy:-y}
    if [[ "$add_proxy" == "y" || "$add_proxy" == "Y" ]]; then
        echo -e "${BLUE}--- 添加一个TCP代理 ---${NC}"
        read -rp "请输入代理名称 (例如 ssh_proxy): " proxy_name; proxy_name=${proxy_name:-ssh_$(date +%s)}
        read -rp "请输入要转发的本地IP [默认为 127.0.0.1]: " local_ip; local_ip=${local_ip:-127.0.0.1}
        read -rp "请输入要转发的本地端口 (例如 SSH的22端口): " local_port; local_port=${local_port:-22}
        read -rp "请输入服务端要监听的远程端口 (remotePort): " remote_port; remote_port=${remote_port:-6000}

        sudo tee -a "$FRPC_CONFIG_FILE" > /dev/null <<EOF

[[proxies]]
name = "$proxy_name"
type = "tcp"
localIP = "$local_ip"
localPort = $local_port
remotePort = $remote_port
EOF
        echo -e "${GREEN}代理 [${proxy_name}] 添加成功！${NC}"
        echo -e "${YELLOW}您现在可以通过 ssh -p ${remote_port} user@${server_addr} 来访问此机器的SSH服务。${NC}"
    fi
    echo -e "${YELLOW}您可以随时手动编辑 ${FRPC_CONFIG_FILE} 来添加更多代理。${NC}"
}

setup_systemd_frpc() {
    echo -e "${BLUE}正在为 frpc 创建 systemd 服务...${NC}"
    sudo tee "${SYSTEMD_PATH}/frpc.service" > /dev/null <<EOF
[Unit]
Description=Frp Client Service
After=network.target
[Service]
Type=simple
User=root
Restart=on-failure
RestartSec=5s
ExecStart=/usr/bin/frpc -c ${FRPC_CONFIG_FILE}
[Install]
WantedBy=multi-user.target
EOF
    sudo systemctl daemon-reload; sudo systemctl enable frpc; sudo systemctl start frpc
    sleep 2
    if systemctl is-active --quiet frpc; then echo -e "${GREEN}frpc 服务已成功启动！${NC}"; else
        echo -e "${RED}错误：frpc 服务启动失败，请检查日志。${NC}"; fi
}

install_frpc() {
    local version_opt="$1"
    echo -e "${BLUE}--> 开始安装 frpc (客户端)...${NC}"
    if ! download_and_extract "$version_opt"; then return; fi
    sudo mkdir -p "$FRP_BASE_PATH"
    sudo cp "${FRP_TMP_PATH}/frpc" "${FRP_BASE_PATH}/frpc"
    sudo ln -sfn "${FRP_BASE_PATH}/frpc" "/usr/bin/frpc"
    sudo chmod +x "/usr/bin/frpc"
    configure_frpc
    setup_systemd_frpc
    rm -rf "/tmp/frp.tar.gz" "${FRP_TMP_PATH}"
}

show_frpc_info() {
    if [ ! -f "$FRPC_CONFIG_FILE" ]; then echo -e "${RED}错误：未找到客户端配置文件。${NC}"; return; fi
    clear
    echo -e "${YELLOW}======================================================${NC}"
    echo -e "${GREEN}         frpc (客户端) - 当前配置文件内容          ${NC}"
    echo -e "${YELLOW}======================================================${NC}"
    echo -e "${BLUE}"
    sudo cat "$FRPC_CONFIG_FILE"
    echo -e "${NC}"
    echo -e "${YELLOW}======================================================${NC}"
}

uninstall_frpc() {
    read -rp "$(echo -e ${RED}"警告：此操作将彻底卸载 frpc 并删除其配置文件！确定吗？ (y/n): "${NC})" confirm
    if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then echo -e "${YELLOW}操作已取消。${NC}"; return; fi
    stop_and_disable_service "frpc"
    sudo rm -f "/usr/bin/frpc" "${FRP_BASE_PATH}/frpc" "${SYSTEMD_PATH}/frpc.service" "$FRPC_CONFIG_FILE"
    sudo systemctl daemon-reload
    echo -e "${GREEN}frpc 已成功卸载。${NC}"
}

# --- 新增功能函数 ---

show_service_status() {
    local service_name="$1"
    local friendly_name="$2"
    
    if systemctl is-active --quiet "$service_name"; then
        echo -e "  ${friendly_name}服务状态: ${GREEN}运行中${NC}"
    else
        echo -e "  ${friendly_name}服务状态: ${RED}未运行${NC}"
    fi
    
    if systemctl is-enabled --quiet "$service_name"; then
        echo -e "  开机自启状态: ${GREEN}已启用${NC}"
    else
        echo -e "  开机自启状态: ${YELLOW}未启用${NC}"
    fi
}

view_service_logs() {
    local service_name="$1"
    local friendly_name="$2"
    
    if ! systemctl is-active --quiet "$service_name"; then
        echo -e "${YELLOW}${friendly_name}服务未运行，无日志可查看。${NC}"
        press_any_key
        return
    fi
    
    clear
    echo -e "${YELLOW}======================================================${NC}"
    echo -e "${GREEN}        ${friendly_name}服务日志 - 按 q 退出查看          ${NC}"
    echo -e "${YELLOW}======================================================${NC}"
    sudo journalctl -u "$service_name" -n 20 --no-pager
    echo -e "${YELLOW}======================================================${NC}"
    echo -e "提示：按 ${GREEN}q${NC} 键退出日志查看"
    journalctl -u "$service_name" -f
}

# --- 菜单系统 ---

frps_menu() {
    while true; do
        clear
        echo -e "${GREEN}======================================================${NC}"
        echo -e "${GREEN}--- frps (服务端) 管理菜单 ---${NC}"
        show_service_status "frps" "frps"
        echo -e "${GREEN}======================================================${NC}"
        echo -e " 1. 安装 frps (自动最新版)"
        echo -e " 2. 安装 frps (指定 v0.61.0 版)"
        echo -e " 3. 手动指定版本号安装 (从GitHub选择)"
        echo -e " 4. 重新安装/更新 frps (保留配置)"
        echo -e " 5. 显示 frps 连接信息"
        echo -e " 6. 查看 frps 日志"
        echo -e " 7. 编辑 frps 配置文件"
        echo -e " 8. 卸载 frps"
        echo -e " 0. 返回主菜单"
        echo -e "${GREEN}======================================================${NC}"
        read -rp "请输入选择 [0-8]: " choice
        case $choice in
            1) stop_and_disable_service "frps"; sudo rm -rf "$FRPS_CONFIG_FILE" "$FRPS_INFO_LOG"; install_frps "latest"; press_any_key ;;
            2) stop_and_disable_service "frps"; sudo rm -rf "$FRPS_CONFIG_FILE" "$FRPS_INFO_LOG"; install_frps "specified"; press_any_key ;;
            3) 
                read -rp "请输入要安装的frp版本号 (例如v0.52.0): " custom_version
                if [[ "$custom_version" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
                    stop_and_disable_service "frps"; sudo rm -rf "$FRPS_CONFIG_FILE" "$FRPS_INFO_LOG"
                    install_frps "$custom_version"
                else
                    echo -e "${RED}无效的版本号格式，请使用类似 v0.52.0 的格式${NC}"
                fi
                press_any_key 
                ;;
            4) if [ ! -f "$FRPS_CONFIG_FILE" ]; then echo -e "${RED}未找到配置，无法更新。${NC}"; else stop_and_disable_service "frps"; install_frps "latest"; fi; press_any_key ;;
            5) show_frps_info; press_any_key ;;
            6) view_service_logs "frps" "frps"; press_any_key ;;
            7) 
                sudo vim "$FRPS_CONFIG_FILE"
                read -rp "是否重启服务以使配置生效？(y/n) [默认为 y]: " restart_choice; restart_choice=${restart_choice:-y}
                if [[ "$restart_choice" == "y" || "$restart_choice" == "Y" ]]; then
                    sudo systemctl restart frps
                    echo -e "${GREEN}服务已重启！${NC}"
                fi
                press_any_key 
                ;;
            8) uninstall_frps; press_any_key ;;
            0) return ;;
            *) echo -e "${RED}无效输入!${NC}"; sleep 1 ;;
        esac
    done
}

frpc_menu() {
    while true; do
        clear
        echo -e "${GREEN}======================================================${NC}"
        echo -e "${GREEN}--- frpc (客户端) 管理菜单 ---${NC}"
        show_service_status "frpc" "frpc"
        echo -e "${GREEN}======================================================${NC}"
        echo -e " 1. 安装 frpc (自动最新版)"
        echo -e " 2. 安装 frpc (指定 v0.61.0 版)"
        echo -e " 3. 手动指定版本号安装 (从GitHub选择)"
        echo -e " 4. 重新安装/更新 frpc (保留配置)"
        echo -e " 5. 查看/编辑 frpc 配置文件"
        echo -e " 6. 查看 frpc 日志"
        echo -e " 7. 卸载 frpc"
        echo -e " 0. 返回主菜单"
        echo -e "${GREEN}======================================================${NC}"
        read -rp "请输入选择 [0-7]: " choice
        case $choice in
            1) stop_and_disable_service "frpc"; sudo rm -f "$FRPC_CONFIG_FILE"; install_frpc "latest"; press_any_key ;;
            2) stop_and_disable_service "frpc"; sudo rm -f "$FRPC_CONFIG_FILE"; install_frpc "specified"; press_any_key ;;
            3) 
                read -rp "请输入要安装的frp版本号 (例如v0.52.0): " custom_version
                if [[ "$custom_version" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
                    stop_and_disable_service "frpc"; sudo rm -f "$FRPC_CONFIG_FILE"
                    install_frpc "$custom_version"
                else
                    echo -e "${RED}无效的版本号格式，请使用类似 v0.52.0 的格式${NC}"
                fi
                press_any_key 
                ;;
            4) if [ ! -f "$FRPC_CONFIG_FILE" ]; then echo -e "${RED}未找到配置，无法更新。${NC}"; else stop_and_disable_service "frpc"; install_frpc "latest"; fi; press_any_key ;;
            5) 
                sudo vim "$FRPC_CONFIG_FILE"
                read -rp "是否重启服务以使配置生效？(y/n) [默认为 y]: " restart_choice; restart_choice=${restart_choice:-y}
                if [[ "$restart_choice" == "y" || "$restart_choice" == "Y" ]]; then
                    sudo systemctl restart frpc
                    echo -e "${GREEN}服务已重启！${NC}"
                fi
                press_any_key 
                ;;
            6) view_service_logs "frpc" "frpc"; press_any_key ;;
            7) uninstall_frpc; press_any_key ;;
            0) return ;;
            *) echo -e "${RED}无效输入!${NC}"; sleep 1 ;;
        esac
    done
}

check_initial_status() {
    clear
    echo -e "${BLUE}=====================================================${NC}"
    echo -e "${BLUE}                 frp 管理脚本 by 错弦序                 ${NC}"
    echo -e "${BLUE}=====================================================${NC}"
    echo -e "正在检测现有服务状态..."
    if systemctl is-active --quiet frps; then
        echo -e "  - 服务端 (frps): ${GREEN}已安装并正在运行${NC}"
    else
        echo -e "  - 服务端 (frps): ${RED}未安装或未运行${NC}"
    fi
    if systemctl is-active --quiet frpc; then
        echo -e "  - 客户端 (frpc): ${GREEN}已安装并正在运行${NC}"
    else
        echo -e "  - 客户端 (frpc): ${RED}未安装或未运行${NC}"
    fi
    echo -e "${BLUE}=====================================================${NC}\n"
}

main_menu() {
    while true; do
        check_initial_status
        echo -e "请选择您要管理的服务端："
        echo -e " ${YELLOW}1. 管理 frps (服务端)${NC}"
        echo -e " ${YELLOW}2. 管理 frpc (客户端)${NC}"
        echo -e " ${YELLOW}0. 退出脚本${NC}"
        read -rp "请输入您的选择 [0-2]: " choice
        case $choice in
            1) frps_menu ;;
            2) frpc_menu ;;
            0) echo -e "${GREEN}感谢使用，脚本退出。${NC}"; exit 0 ;;
            *) echo -e "${RED}无效输入!${NC}"; sleep 1 ;;
        esac
    done
}

# --- 脚本入口 ---
check_root
check_dependencies
main_menu